<template>
  <!-- 工单表表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="1500"
    draggable
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="80px"
      class="sketch_content"
    >
      <el-row>
        <!--<el-col :span="8">
          <el-form-item label="产品" prop="materialCode">
            <el-input
              v-model="formData.materialCode"
              placeholder="请输入产品"
              clearable
              readonly
              @click="showWorkOrderSelect"
              style="width: 220px"
            >
              <template #append>
                <el-button @click="resetMaterial">清除</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>-->
        <!--        <el-col :span="4">
          <el-form-item label="日期" prop="requireDate">
            <el-date-picker
              v-model="formData.requireDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="">
            <el-button type="primary" @click="getPlanWorkingForm"
              >查询</el-button
            >
            &lt;!&ndash;<el-button @click="resetForm">重置</el-button>&ndash;&gt;
          </el-form-item>
        </el-col>-->
      </el-row>
      <el-card shadow="never" class="table-container">
        <div class="formTable2">
          <el-table
            :data="formData.details"
            :key="Math.random"
            border
            style="width: 100%"
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            />
            <el-table-column
              label="产品名称"
              props="materialName"
              min-width="150"
            >
              <template #default="{ row }">
                {{ row.materialName }}
              </template>
            </el-table-column>
            <el-table-column
              label="日期"
              prop="requireDate"
              min-width="130"
              align="center"
              :formatter="formatDate"
            />
            <el-table-column
              label="冷起"
              prop="isHead"
              min-width="100"
              show-overflow-tooltip
              header-align="center"
              align="center"
            >
              <template #default="{ row }">
                <span v-if="row.isHead == 1">是</span>
                <span v-else>否</span>
              </template>
            </el-table-column>
            <el-table-column
              label="留线"
              prop="isTail"
              min-width="100"
              show-overflow-tooltip
              header-align="center"
              align="center"
            >
              <template #default="{ row }">
                <span v-if="row.isTail == 1">是</span>
                <span v-else>否</span>
              </template>
            </el-table-column>
            <el-table-column
              label="数量"
              prop="amount"
              min-width="100"
              show-overflow-tooltip
              header-align="center"
              align="right"
            />
            <el-table-column
              label="模数"
              prop="planQuantity"
              min-width="100"
              show-overflow-tooltip
              header-align="center"
              align="right"
            />
            <el-table-column
              label="计划包数"
              prop="planPackage"
              min-width="100"
              show-overflow-tooltip
              header-align="center"
              align="right"
            />
            <el-table-column
              label="计划炉数"
              prop="planStove"
              min-width="100"
              show-overflow-tooltip
              header-align="center"
              align="right"
            />
          </el-table>
        </div>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="formData.details.length > 0"
          type="danger"
          :loading="loading"
          @click="handleSubmit"
          >撤 回</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
    <conten-select
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :plantId="formData.plantId"
      :brekList="brekList"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "GENERATIONDAYPLAN",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (newVal) {
      getPlanWorkingForm();
    }
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  // materialCode: [{ required: true, message: "请输入产品", trigger: "change" }],
  // requireDate: [{ required: true, message: "请选择日期", trigger: "change" }],
  sonshiftId: [{ required: true, message: "请选择班次", trigger: "change" }],
  shiftSystemId: [{ required: true, message: "请选择班制", trigger: "change" }],
  stoveNum: [{ required: true, message: "请选择炉号", trigger: "change" }],
  equipInfoId: [{ required: true, message: "请选择设备", trigger: "change" }],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  producePlanCode: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  workSequence: "",
  planNum: "",
  requireDate: "",
  planQuantity: "",
  planStatus: "",
  productionVersionNumber: "",
  externalCode: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
  shiftSystemId: "",
  status: 1,
  details: [],
  equipInfoId: [],
  isPlanRetract: 1,
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        producePlanCode,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        materialId,
        materialCode,
        materialName,
        workSequence,
        planNum,
        requireDate,
        planQuantity,
        planStatus,
        productionVersionNumber,
        externalCode,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        producePlanCode,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        materialId,
        materialCode,
        materialName,
        workSequence,
        planNum,
        requireDate,
        planQuantity,
        planStatus,
        productionVersionNumber,
        externalCode,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.clearValidate();
  formRef.value.resetFields();
  formData.id = "";
  formData.producePlanCode = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.workSequence = "";
  formData.planNum = "";
  formData.requireDate = "";
  formData.planQuantity = "";
  formData.planStatus = "";
  formData.productionVersionNumber = "";
  formData.externalCode = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
  formData.details = [];
  shiftList.value = [];
  details.value = {};
  existEquipInfoList.value = [];
  existEquipInfoIdList.value = [];
  formData.isPlanRetract = 1;
}
const loading = ref(false);

/** 工单表保存提交 */
async function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      formData.details.forEach((item: any, index: number) => {
        item.workSequence = index + 1;
      });
      loading.value = true;
      const res = await request({
        url: "/mes/mesplanmonthplanactual/planRetract",
        method: "post",
        data: formData.details,
      }).finally(() => {
        loading.value = false;
      });
      if (res.code === 200) {
        ElMessage.success(`撤回成功`);
        closeDialog();
        emit("reset-table", formData.id);
      }
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
onMounted(() => {
  // getShiftSetList();
  // getEquipInfoListList();
});
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};
//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    formData.materialId = data.id;
    formData.materialCode = data.materialCode;
  }
};
// 回显的数据
const brekList = ref([]);
const resetMaterial = () => {
  formData.materialId = "";
  formData.materialCode = "";
};

// 获取当前日期yyyymmdd
function getCurrentDate() {
  const today = new Date();
  let year = today.getFullYear();
  let month = (today.getMonth() + 1).toString().padStart(2, "0");
  let day = today.getDate().toString().padStart(2, "0");
  return year.toString() + "-" + month + "-" + day;
}
//设备
const equipInfoList = ref([]);
async function getEquipInfoListList() {
  await request({
    url: "mdm/mdmequipInfo/getList",
    method: "post",
    data: { plantId: formData.plantId, enabled: 1 },
  }).then((res) => {
    equipInfoList.value = res.data;
  });
}
const existEquipInfoIdList = ref([]);
const existEquipInfoList = ref([]);
const changeExistEquipInfo = () => {
  formData.equipInfoId = existEquipInfoIdList.value.join(",");
  existEquipInfoList.value = existEquipInfoIdList.value
    .map((id) => equipInfoList.value.find((item) => item.id === id))
    .filter((item) => item !== undefined);
};
//班制
const shiftSetList = ref([]);
async function getShiftSetList() {
  await request({
    url: "mes/messhiftset/getList",
    method: "post",
    data: { plantId: formData.plantId, enabled: 1 },
  }).then((res) => {
    shiftSetList.value = res.data;
  });
}
function changeShiftSet(val) {
  formData.shiftSystemId = val;
  shiftList.value = [];
  if (val) {
    getShifts();
    if (formData.details.length > 0) {
      formData.details.forEach((item) => {
        item.shiftSystemId = val;
      });
    }
  }
}

//班次
const shiftList = ref([]);
async function getShifts() {
  await request({
    url: "mes/messhiftset/getDetails",
    method: "post",
    data: {
      id: formData.shiftSystemId,
    },
  }).then((res) => {
    shiftList.value = res.data;
    formData.details.forEach((item, index) => {
      item.shiftId = shiftList.value[0].shiftId;
      item.shiftCode = shiftList.value[0].shiftCode;
    });
  });
}
//获取查询条件下的工单列表
const details = ref();
async function getPlanWorkingForm() {
  // if (!formData.requireDate) {
  //   ElMessage.error(`请选择日期`);
  //   return;
  // }
  await request({
    url: "/mes/mesplanmonthplanactual/getPlanList",
    method: "post",
    data: formData,
  }).then((res: any) => {
    if (res.code == 200) {
      formData.details = res.data;
    }
  });
}
//智能排序
async function smartSort() {
  if (formData.details.length == 0) {
    ElMessage.error(`请选择获取数据`);
    return;
  }
  if (existEquipInfoIdList.value.length == 0) {
    ElMessage.error(`请选择设备`);
    return;
  }
  if (!formData.shiftSystemId) {
    ElMessage.error(`请选择班制`);
    return;
  }
  await request({
    url: "/mes/mesplanmonthplanactual/sortBatchDayPlan",
    method: "post",
    data: {
      list: formData.details,
      shiftSetDTO: shiftSetList.value.find(
        (item) => item.id == formData.shiftSystemId
      ),
      listEquip: existEquipInfoList.value,
    },
  }).then((res: any) => {
    if (res.code == 200) {
      formData.details = res.data;
    }
  });
}
const moveUp = (index: number) => {
  const temp = formData.details[index];
  formData.details.splice(index, 1);
  formData.details.splice(index - 1, 0, temp);
};
const shiftDown = (index: number) => {
  const temp = formData.details[index];
  formData.details.splice(index, 1);
  formData.details.splice(index + 1, 0, temp);
};
function changeEquipInfo(index: number, code: any) {
  if (code) {
    existEquipInfoList.value.forEach((item: any) => {
      if (item.equipCode == code) {
        formData.details[index].deviceId = item.id;
        formData.details[index].stoveNum = item.equipCode;
        formData.details[index].deviceName = item.equipName;
      }
    });
  } else {
    formData.details[index].deviceId = "";
    formData.details[index].stoveNum = "";
    formData.details[index].deviceName = "";
  }
}
//时间格式处理，yyyy-mm-dd
function formatDate(row, column) {
  const date = row[column.property];
  if (!date) return "";
  return date.split(" ")[0]; // 返回日期的年月日部分，而隐藏时间部分
}
</script>
<style lang="scss" scoped>
.sketch_content {
  // 必须有高度 overflow 为自动
  overflow: auto;
  height: 750px;
}

// 滚动条的样式,宽高分别对应横竖滚动条的尺寸
.sketch_content::-webkit-scrollbar {
  width: 3px;
}

// 滚动条里面默认的小方块,自定义样式
.sketch_content::-webkit-scrollbar-thumb {
  background: #8798af;
  border-radius: 2px;
}

// 滚动条里面的轨道
.sketch_content::-webkit-scrollbar-track {
  background: transparent;
}
</style>
